package router

import (
	"GinWeb/controllers"
	"GinWeb/services"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 身份验证中间件
func authenticate() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头中获取userId
		userId, err := strconv.Atoi(c.Request.Header.Get("userId"))
		if err != nil {
			// 如果转换失败，返回错误
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid userID in Header"})
			c.Abort() // 阻止后续处理
			return
		}
		// 将用户ID存储在Gin的上下文中
		c.Set("userId", userId)

		// 继续处理请求
		c.Next()
	}
}

func Router() *gin.Engine {
	r := gin.Default()
	r.Use(authenticate())
	msgNotify := r.Group("/msgNotify")
	{
		msgService := services.NewMsgService()
		msgController := controllers.NewMsgController(msgService)
		// 获取某用户的提示信息列表
		msgNotify.GET("/", msgController.GetMsgNotifyList)
		msgNotify.POST("/add", msgController.AddMsgNotify)
		msgNotify.PUT("/update/:id", msgController.UpdateMsgNotify)
		msgNotify.DELETE("/delete/:id", msgController.DeleteMsgNotify)
	}
	return r
}
